package com.polaris.live.common.network.state

import androidx.lifecycle.MutableLiveData
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.BaseResponse
import com.polaris.live.common.network.ExceptionHandler
import com.polaris.live.common.network.HTTP_ERROR_CODE

/**
 * 自定义结果集封装类
 *
 * @author Created by 半仙 on 2023/7/31/031 16:41
 */
sealed class ResultState<out T> {

    companion object {

        fun <T> onAppSuccess(data: T): ResultState<T> = Success(data)

        fun <T> onAppError(error: AppException): ResultState<T> = Error(error)
    }

    data class Success<out T>(val data: T) : ResultState<T>()

    data class Error(val error: AppException) : ResultState<Nothing>()

}

/**
 * 处理返回值
 * @param result 请求结果
 */
fun <T> MutableLiveData<ResultState<T>>.paresResult(result: BaseResponse<T>) {
    value = when {
        result.isSuccess() -> {
            val data = result.getResponseData()
            if (data == null) {
                ResultState.onAppError(AppException(HTTP_ERROR_CODE, "Data is null"))
            } else {
                ResultState.onAppSuccess(data)
            }
        }
        else -> {
            ResultState.onAppError(
                AppException(
                    result.getResponseCode(),
                    result.getResponseMsg(),
                    result.getErrorExt()
                )
            )
        }
    }
}

/**
 * 不处理返回值 直接返回请求结果
 * @param result 请求结果
 */
fun <T> MutableLiveData<ResultState<T>>.paresResult(result: T) {
    value = ResultState.onAppSuccess(result)
}

/**
 * 异常转换异常处理
 */
fun <T> MutableLiveData<ResultState<T>>.paresException(e: Throwable) {
    this.value = ResultState.onAppError(ExceptionHandler.handleException(e))
}

